// 目录树管理类
class DirectoryTree {
    constructor() {
        this.currentPath = '';
        this.treeData = null;
        this.isLoading = false;
        this.expandedPaths = new Set();
        
        this.initializeElements();
        this.bindEvents();
        this.loadDirectoryTree();
    }

    initializeElements() {
        this.sidebar = document.getElementById('sidebar');
        this.treeContainer = document.querySelector('.directory-tree');
        this.loadingIndicator = document.querySelector('.tree-loading');
        this.refreshBtn = document.querySelector('.refresh-btn');
        this.toggleBtn = document.querySelector('.toggle-btn');
    }

    bindEvents() {
        // 刷新按钮
        if (this.refreshBtn) {
            this.refreshBtn.addEventListener('click', () => {
                this.loadDirectoryTree();
            });
        }

        // 切换侧边栏显示/隐藏
        if (this.toggleBtn) {
            this.toggleBtn.addEventListener('click', () => {
                this.toggleSidebar();
            });
        }

        // 树节点点击事件委托
        if (this.treeContainer) {
            this.treeContainer.addEventListener('click', (e) => {
                this.handleTreeClick(e);
            });
        }
    }

    async loadDirectoryTree(path = '') {
        if (this.isLoading) return;
        
        this.isLoading = true;
        this.showLoading(true);

        try {
            const response = await fetch(`/api/filesystem/tree?path=${encodeURIComponent(path)}`);
            const result = await response.json();

            if (result.success) {
                this.treeData = result.data;
                this.currentPath = path;
                this.renderTree();
            } else {
                this.showError('加载目录树失败: ' + result.message);
            }
        } catch (error) {
            console.error('Failed to load directory tree:', error);
            this.showError('加载目录树失败: ' + error.message);
        } finally {
            this.isLoading = false;
            this.showLoading(false);
        }
    }

    renderTree() {
        if (!this.treeData || !this.treeContainer) return;

        this.treeContainer.innerHTML = '';
        this.renderTreeNode(this.treeData, this.treeContainer, 0);
    }

    renderTreeNode(node, container, level) {
        const item = document.createElement('div');
        item.className = 'tree-item';
        item.dataset.path = node.path;
        item.dataset.type = node.type;
        item.style.paddingLeft = `${level * 20 + 10}px`;

        // 添加类型特定的样式
        if (node.type === 'directory') {
            item.classList.add('directory');
        } else {
            item.classList.add('file');
            if (node.name.toLowerCase().endsWith('.md')) {
                item.classList.add('markdown');
            }
        }

        // 创建展开/折叠按钮
        const expandBtn = document.createElement('span');
        expandBtn.className = 'tree-expand';
        
        if (node.type === 'directory') {
            const isExpanded = this.expandedPaths.has(node.path);
            expandBtn.classList.add(isExpanded ? 'expanded' : 'collapsed');
            expandBtn.innerHTML = isExpanded ? '▼' : '▶';
        } else {
            expandBtn.classList.add('leaf');
            expandBtn.innerHTML = '';
        }

        // 创建图标
        const icon = document.createElement('span');
        icon.className = 'tree-icon';
        if (node.type === 'directory') {
            icon.innerHTML = '📁';
        } else if (node.name.toLowerCase().endsWith('.md')) {
            icon.innerHTML = '📝';
        } else {
            icon.innerHTML = '📄';
        }

        // 创建文件名
        const name = document.createElement('span');
        name.className = 'tree-name';
        name.textContent = node.name;

        item.appendChild(expandBtn);
        item.appendChild(icon);
        item.appendChild(name);
        container.appendChild(item);

        // 如果是目录且已展开，渲染子节点
        if (node.type === 'directory' && node.children && this.expandedPaths.has(node.path)) {
            const childrenContainer = document.createElement('div');
            childrenContainer.className = 'tree-children';
            
            node.children.forEach(child => {
                this.renderTreeNode(child, childrenContainer, level + 1);
            });
            
            container.appendChild(childrenContainer);
        }
    }

    handleTreeClick(e) {
        const item = e.target.closest('.tree-item');
        if (!item) return;

        const path = item.dataset.path;
        const type = item.dataset.type;
        const expandBtn = item.querySelector('.tree-expand');

        if (e.target === expandBtn && type === 'directory') {
            // 点击展开/折叠按钮
            this.toggleDirectory(path, item);
        } else if (type === 'file') {
            // 点击文件
            this.selectFile(path, item);
        } else if (type === 'directory') {
            // 点击目录名称，也进行展开/折叠
            this.toggleDirectory(path, item);
        }
    }

    async toggleDirectory(path, item) {
        const expandBtn = item.querySelector('.tree-expand');
        const isExpanded = this.expandedPaths.has(path);

        if (isExpanded) {
            // 折叠目录
            this.expandedPaths.delete(path);
            expandBtn.classList.remove('expanded');
            expandBtn.classList.add('collapsed');
            expandBtn.innerHTML = '▶';
            
            // 移除子节点
            const childrenContainer = item.parentNode.querySelector('.tree-children');
            if (childrenContainer) {
                childrenContainer.remove();
            }
        } else {
            // 展开目录
            this.expandedPaths.add(path);
            expandBtn.classList.remove('collapsed');
            expandBtn.classList.add('expanded');
            expandBtn.innerHTML = '▼';
            
            // 加载并显示子节点
            await this.loadDirectoryChildren(path, item);
        }
    }

    async loadDirectoryChildren(path, item) {
        try {
            const response = await fetch(`/api/filesystem/tree?path=${encodeURIComponent(path)}`);
            const result = await response.json();

            if (result.success && result.data.children) {
                const childrenContainer = document.createElement('div');
                childrenContainer.className = 'tree-children';
                
                const level = parseInt(item.style.paddingLeft) / 20;
                result.data.children.forEach(child => {
                    this.renderTreeNode(child, childrenContainer, level + 1);
                });
                
                item.parentNode.appendChild(childrenContainer);
            }
        } catch (error) {
            console.error('Failed to load directory children:', error);
            this.showError('加载目录内容失败: ' + error.message);
        }
    }

    async selectFile(path, item) {
        // 移除之前选中的项目
        const previousSelected = this.treeContainer.querySelector('.tree-item.selected');
        if (previousSelected) {
            previousSelected.classList.remove('selected');
        }

        // 选中当前项目
        item.classList.add('selected');

        // 如果是Markdown文件，加载到编辑器
        if (path.toLowerCase().endsWith('.md')) {
            await this.loadFileToEditor(path);
        }
    }

    async loadFileToEditor(path) {
        try {
            const response = await fetch(`/api/filesystem/file?path=${encodeURIComponent(path)}`);
            const result = await response.json();

            if (result.success) {
                // 获取编辑器实例并设置内容
                const editor = document.getElementById('editor');
                if (editor) {
                    editor.value = result.data.content;
                    
                    // 触发编辑器内容变化事件
                    const event = new Event('input', { bubbles: true });
                    editor.dispatchEvent(event);
                    
                    // 如果有预览功能，更新预览
                    if (typeof updatePreview === 'function') {
                        updatePreview();
                    }
                }
                
                // 更新文档标题（如果有的话）
                this.updateDocumentTitle(path);
                
            } else {
                this.showError('加载文件失败: ' + result.message);
            }
        } catch (error) {
            console.error('Failed to load file:', error);
            this.showError('加载文件失败: ' + error.message);
        }
    }

    updateDocumentTitle(path) {
        const fileName = path.split('/').pop() || path.split('\\').pop();
        document.title = `${fileName} - MarkEdit`;
        
        // 如果有标题显示区域，也更新它
        const titleElement = document.querySelector('.document-title');
        if (titleElement) {
            titleElement.textContent = fileName;
        }
    }

    toggleSidebar() {
        if (this.sidebar) {
            this.sidebar.classList.toggle('collapsed');
            
            // 保存侧边栏状态到本地存储
            const isCollapsed = this.sidebar.classList.contains('collapsed');
            localStorage.setItem('sidebar-collapsed', isCollapsed);
        }
    }

    showLoading(show) {
        if (this.loadingIndicator) {
            this.loadingIndicator.style.display = show ? 'block' : 'none';
        }
        
        if (this.refreshBtn) {
            this.refreshBtn.disabled = show;
        }
    }

    showError(message) {
        // 创建错误提示
        const errorDiv = document.createElement('div');
        errorDiv.className = 'tree-error';
        errorDiv.innerHTML = `
            <div class="error-icon">⚠️</div>
            <div class="error-message">${message}</div>
        `;
        
        if (this.treeContainer) {
            this.treeContainer.innerHTML = '';
            this.treeContainer.appendChild(errorDiv);
        }
        
        // 3秒后自动隐藏错误信息
        setTimeout(() => {
            if (errorDiv.parentNode) {
                errorDiv.remove();
            }
        }, 3000);
    }

    // 初始化侧边栏状态
    initializeSidebarState() {
        const isCollapsed = localStorage.getItem('sidebar-collapsed') === 'true';
        if (isCollapsed && this.sidebar) {
            this.sidebar.classList.add('collapsed');
        }
    }
}

// 当DOM加载完成后初始化目录树
document.addEventListener('DOMContentLoaded', () => {
    // 检查是否存在目录树容器
    if (document.querySelector('.directory-tree')) {
        window.directoryTree = new DirectoryTree();
        window.directoryTree.initializeSidebarState();
    }
});